<template>
  <div class="User-container">
    <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
    <el-button type="danger" @click="batchDel">批量删除</el-button>
    <el-table
      :data="userList"
      style="width: 100%; margin-top: 12px"
      @selection-change="selectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="120" />
      <el-table-column prop="loginAct" label="账号" width="120" show-overflow-tooltip />
      <el-table-column prop="name" label="姓名" width="120" show-overflow-tooltip />
      <el-table-column prop="phone" label="手机" show-overflow-tooltip />
      <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
      <el-table-column prop="createTime" label="创建时间" show-overflow-tooltip />
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleView(scope.row.id)">
            查看
          </el-button>
          <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">
            编辑
          </el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="total"
      background
      layout="prev, pager, next"
      :page-size="pageSize"
      :total="total"
      class="pagination"
      @change="pageChange"
      @prev-click="toPage"
      @next-click="toPage"
    />

    <el-dialog v-model="userAddDialogFormVisible" :title="userAddDialogTitle" width="55%">
      <el-form :model="userAddForm" ref="userAddFormRef" :rules="rules" label-width="110px">
        <el-form-item label="账号" prop="loginAct">
          <el-input v-model="userAddForm.loginAct" />
        </el-form-item>
        <el-form-item label="密码" prop="loginPwd" v-if="!userAddForm.id">
          <el-input v-model="userAddForm.loginPwd" type="password" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userAddForm.name" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userAddForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userAddForm.email" />
        </el-form-item>
        <el-form-item label="账号未过期" prop="accountNoExpired">
          <el-select v-model="userAddForm.accountNoExpired" placeholder="请选择">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="密码未过期" prop="credentialsNoExpired">
          <el-select v-model="userAddForm.credentialsNoExpired" placeholder="请选择">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号未锁定" prop="accountNoLocked">
          <el-select v-model="userAddForm.accountNoLocked" placeholder="请选择">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="账号是否可用" prop="accountEnabled">
          <el-select v-model="userAddForm.accountEnabled" placeholder="请选择">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="userAddDialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser(userAddFormRef)"> 提 交 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="User">
import httpRequest from '@/http/httpRequest'
import { onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import type { FormInstance, FormRules } from 'element-plus'
let router = useRouter()
// type Props = {}
// defineProps<Props>()
// const emit = defineEmits([])
// const router = useRouter()
// const route = useRoute()
let total = ref(0)
let pageSize = ref(10)
let selectionDataArr: any[] = []
interface IAddUserForm {
  id: number | null
  loginAct: string | null
  loginPwd: string | null
  name: string | null
  phone: string | null
  email: string | null
  accountNoExpired: number | null
  credentialsNoExpired: number | null
  accountNoLocked: number | null
  accountEnabled: number | null
}
let userAddDialogFormVisible = ref(false)
let userAddDialogTitle = ref('新增用户')
const userAddFormRef = ref<FormInstance>()
const rules = reactive<FormRules<IAddUserForm>>({
  loginAct: [{ required: true, message: '请输入登录账号', trigger: 'blur' }],
  loginPwd: [{ required: true, message: '请输入登录密码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号码', trigger: 'blur' }],
  email: [{ required: true, message: '请输入电子邮箱', trigger: 'blur' }],
  accountNoExpired: [{ required: true, message: '请选择账号是否过期', trigger: 'blur' }],
  credentialsNoExpired: [{ required: true, message: '请选择密码是否过期', trigger: 'blur' }],
  accountNoLocked: [{ required: true, message: '请选择账号是否锁定', trigger: 'blur' }],
  accountEnabled: [{ required: true, message: '请选择账号是否可用', trigger: 'blur' }],
})
let userAddForm = reactive<IAddUserForm>({
  id: null,
  loginAct: '',
  loginPwd: null,
  name: '',
  phone: '',
  email: '',
  accountNoExpired: null,
  credentialsNoExpired: null,
  accountNoLocked: null,
  accountEnabled: null,
})
const showAddUserDialog = () => {
  userAddFormRef.value?.resetFields()
  Object.assign(userAddForm, {
    id: null,
    loginAct: '',
    loginPwd: null,
    name: '',
    phone: '',
    email: '',
    accountNoExpired: null,
    credentialsNoExpired: null,
    accountNoLocked: null,
    accountEnabled: null,
  })
  userAddDialogFormVisible.value = true
  userAddDialogTitle.value = '新增用户'
}
const addUser = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      let formData = new FormData()
      formData.append('loginAct', userAddForm.loginAct + '')
      formData.append('loginPwd', userAddForm.loginPwd + '')
      formData.append('name', userAddForm.name + '')
      formData.append('phone', userAddForm.phone + '')
      formData.append('email', userAddForm.email + '')
      formData.append('accountNoExpired', userAddForm.accountNoExpired + '')
      formData.append('credentialsNoExpired', userAddForm.credentialsNoExpired + '')
      formData.append('accountNoLocked', userAddForm.accountNoLocked + '')
      formData.append('accountEnabled', userAddForm.accountEnabled + '')
      if (userAddForm.id) {
        //修改用户
        formData.append('id', userAddForm.id + '')
        httpRequest
          .doPut('/api/user', formData)
          .then((res) => {
            if (res.data.code == 200) {
              //修改成功
              userAddDialogFormVisible.value = false
              getData(1)
            }
          })
          .catch((error) => {})
      } else {
        //新增用户
        httpRequest
          .doPost('/api/user', formData)
          .then((res) => {
            if (res.data.code == 200) {
              //新增成功
              userAddDialogFormVisible.value = false
              getData(1)
            }
          })
          .catch((error) => {})
      }
    }
  })
}
interface IUser {
  id: number
  loginAct: string
  name: string
  phone: string
  email: string
  createTime: string
}

const userList = ref<IUser[]>([])

const selectionChange = (newSelection: any[]) => {
  console.log('selectionChange', newSelection)
  selectionDataArr = newSelection
}

const batchDel = () => {
  let idArr: string[] = []
  selectionDataArr.map((item) => {
    console.log('batchDel', item.id)
    idArr.push(item.id)
  })
  if (idArr.length <= 0) {
    return
  }
  let ids: string = idArr.join(',')
  httpRequest
    .doDelete('/api/user', {
      ids: ids,
    })
    .then((res) => {
      if (res.data.code == 200) {
        getData(1)
      }
    })
    .catch((error) => {})
}

const handleView = (userId: IUser) => {
  router.push({
    path: '/home/user/' + userId,
  })
}
const handleEdit = (userId: IUser) => {
  userAddFormRef.value?.resetFields()
  userAddDialogTitle.value = '修改用户'
  userAddDialogFormVisible.value = true
  httpRequest
    .doGet('/api/user/' + userId, {})
    .then((res) => {
      if (res.data.code == 200) {
        //userAddForm赋值
        Object.assign(userAddForm, res.data.data)
        userAddDialogFormVisible.value = true
      } else {
      }
    })
    .catch((error) => {})
}
const handleDelete = (userId: IUser) => {
  httpRequest
    .doDelete('/api/user/' + userId, {})
    .then((res) => {
      if (res.data.code == 200) {
        //删除成功
        getData(1)
      }
    })
    .catch((error) => {})
}
const getData = (currentPage: number, pageSize: number = 10) => {
  httpRequest
    .doGet('/api/users', {
      currentPage: currentPage,
      pageSize: pageSize,
    })
    .then((res) => {
      if (res.data.code == 200) {
        userList.value = res.data.data.list || []
        total.value = res.data.data.total
      }
    })
    .catch((error) => {})
}
onMounted(() => {
  getData(1)
})

let pageChange = (currentPage: number, pageSize: number) => {
  getData(currentPage, pageSize)
}

let toPage = (currentPage: number) => {
  getData(currentPage, pageSize.value)
}
</script>

<style scoped lang="scss">
.User-container {
  min-height: 100%;

  .pagination {
    justify-content: flex-end;
    margin-top: 12px;
  }
}
</style>
